package com.boc.news.server;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.boc.ibatis.config.JndiDataSource;
import com.boc.news.beans.GlobalP;


public class ImageUploadServlet extends HttpServlet {
	private static final long serialVersionUID = -8300873721073851252L;
	public void init(ServletConfig servletConfig) throws ServletException {
		super.init();
	}
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		StringBuffer sql = new StringBuffer();
		
		sql.append("insert into image.t_img_image (N_XCBH,C_GS,C_MC,N_SIZE,C_PATH,D_SCSJ,C_ZT,C_SFSH) ");
		sql.append("value (?,?,?,?,?,?,?,?)");
		
		String sql0 = "update image.t_img_user set n_ysykj = n_ysykj + ? where n_userid = ?";
		
		Connection con = null;
		PreparedStatement ps = null;
		try {
			Enumeration<?> er = request.getParameterNames();
			request.setCharacterEncoding("UTF-8");
			DiskFileItemFactory factory = new DiskFileItemFactory();
			factory.setSizeThreshold(10240000);// 10M
			File file = new File(GlobalP.BASE_FOLDER_PATH);
			if (!file.exists()) {
				file.mkdirs();
			}
			factory.setRepository(file);
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setFileSizeMax(10002400000l);// 100M
			upload.setSizeMax(10002400000l);// 1000M
			upload.setHeaderEncoding("UTF-8");
			List<?> items = upload.parseRequest(request);
			FileItem item = null;
			for (int i = 0; i < items.size(); i++) {
				item = (FileItem) items.get(i);
				if (!item.isFormField() && item.getName().length() > 0) {
					String name = item.getName();
//					System.out.println(name+"\t大小："+item.getSize());
					String fileName = name.substring(0,name.lastIndexOf("."));
					String gs = name.substring(name.lastIndexOf(".") + 1,name.length());
					String albumsId = request.getParameter("albumsId");
					String userId = request.getParameter("userId");
					String uuid = getUUID();
					String folder = userId + File.separator + albumsId + File.separator;
					
					// 开始事务
					con = JndiDataSource.ds.getConnection();
					con.setAutoCommit(false);
					ps = con.prepareStatement(sql.toString());
					ps.setObject(1, albumsId);
					ps.setObject(2, gs);
					ps.setObject(3, fileName.length() > 32 ? fileName.substring(0, 32):fileName);
					ps.setObject(4, item.getSize() / 1024);
					ps.setObject(5, folder + uuid + "." + gs);
					ps.setObject(6, new Date());
					ps.setObject(7, "1");
					ps.setObject(8, "0");
					int v = ps.executeUpdate();
					
					ps = con.prepareStatement(sql0);
					ps.setObject(1,item.getSize() / 1024);
					ps.setObject(2, userId);
					ps.executeUpdate();
					
					//保存文件
					file = new File(GlobalP.BASE_FOLDER_PATH + File.separator + folder);
					if (!file.exists()) {
						file.mkdirs();
					}
					item.write(new File(GlobalP.BASE_FOLDER_PATH + File.separator + folder + uuid + "." + gs));
//					// 提交事务
					con.commit();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			try {
				con.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
				throw new IOException(e.getMessage());
			}
			throw new IOException(e.getMessage());
		} finally {
			if(ps != null) {
				try {
					ps.close();
				} catch (SQLException e) {
					e.printStackTrace();
					throw new IOException(e.getMessage());
				}
				ps = null;
			}
			if(con != null) {
				try {
					con.close();
				} catch (SQLException e) {
					e.printStackTrace();
					throw new IOException(e.getMessage());
				}
				con = null;
			}
		}
	}

	private static String getUUID() {
		String uuid = UUID.randomUUID().toString();
		StringBuffer uid = new StringBuffer();
		uid.append(uuid.substring(0, 8)).append(uuid.substring(9, 13));
		uid.append(uuid.substring(14, 18)).append( uuid.substring(19, 23));
		uid.append(uuid.substring(24));
		return uid.toString();
	}
}